package com.sondertara.joya.core.jdbc.tran;

import com.sondertara.joya.core.jdbc.callback.TransactionCallback;

/**
 * @author 赵永春 (zyc@hasor.net)
 * @version : 2015年10月22日
 */
public class TransactionTemplateManager implements TransactionTemplate {
    private final TransactionManager transactionManager;

    public TransactionTemplateManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public <T> T execute(TransactionCallback<T> callBack, Propagation behavior, Isolation level) throws Throwable {
        TransactionStatus tranStatus = null;
        try {
            tranStatus = this.transactionManager.begin(behavior, level);
            return callBack.doTransaction(tranStatus);
        } catch (Throwable e) {
            if (tranStatus != null) {
                tranStatus.setRollback();
            }
            throw e;
        } finally {
            if (tranStatus != null && !tranStatus.isCompleted()) {
                this.transactionManager.commit(tranStatus);
            }
        }
    }
}